﻿using System.Collections.Generic;
using IcicleFramework.Camera2D;
using IcicleFramework.Components;
using IcicleFramework.Entities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace IcicleFramework.Rendering
{
    public class Renderer : IRenderer
    {
        private GraphicsDevice graphics;

        private SpriteBatch spriteBatch;

        private BlendState blendState;

        private SamplerState samplerState;

        private DepthStencilState depthStencilState;

        private RasterizerState rasterizerState;

        private Effect effect;

        private Matrix transformMatrix;
        
        public SpriteBatch SpriteBatch
        {
            get { return spriteBatch; }
        }

        public SpriteSortMode SpriteSortMode { get; set; }

        public Renderer(GraphicsDevice graphics, SpriteBatch spriteBatch)
        {
            this.graphics = graphics;
            this.SpriteSortMode = SpriteSortMode.Deferred;
            this.spriteBatch = spriteBatch;
            this.transformMatrix = Matrix.Identity;

            this.blendState = BlendState.AlphaBlend;
            this.samplerState = graphics.SamplerStates[0];
            this.depthStencilState = graphics.DepthStencilState;
            this.rasterizerState = graphics.RasterizerState;
            this.effect = null;
        }

        public void Draw(List<IGameObject> toRender)
        {
            int i, j;

            if (toRender == null) return;

            for (i = 0; i < toRender.Count; i++)
            {
                List<IBaseComponent> components = toRender[i].AllComponents();

                for (j = 0; j < components.Count; j++)
                {
                    IDrawableObject drawable = components[j] as IDrawableObject;

                    if (drawable != null && drawable.Visible)
                    {
                        drawable.Draw(spriteBatch);
                    }
                }
            }
        }

        public void ClearScreen()
        {
            graphics.Clear(Color.Black);
        }

        public void PrepareDraw()
        {
            spriteBatch.Begin(SpriteSortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, Matrix.Identity);
        }

        public void EndDraw()
        {
            spriteBatch.End();
        }
    }
}
